package com.lizemin;

import com.lizemin.spi.Storage;

import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lzm
 * @date 2025/5/29 20:10
 * @description
 */
public class SpiLoader {

    /**
     * 将策略缓存起来，用来提升性能
     */
    private static final ConcurrentHashMap<String, Storage> STORAGE_CACHE = new ConcurrentHashMap<>();

    /**
     * 用来获取某个对象存储服务实现类的实例对象
     *
     * @param strategyName 存储策略的名称，比如AliYunStorage
     * @return Storage存储服务实现类的实例对象
     */
    public static Storage getStorageInstance(String strategyName) {
        if (strategyName == null || strategyName.isEmpty()) {
            throw new RuntimeException("存储策略不能为空");
        }
        Storage instance = STORAGE_CACHE.get(strategyName);
        if (instance != null) {
            return instance;
        }
        ServiceLoader<Storage> storages = ServiceLoader.load(Storage.class);
        for (Storage storage : storages) {
            if (strategyName.equals(storage.getClass().getSimpleName())) {
                STORAGE_CACHE.put(strategyName, storage);
                return storage;
            }
        }
        throw new RuntimeException("未找到对应的存储策略");
    }
}
